<template>
  <div>
    <el-switch v-model="draggable" active-color="#13ce66" inactive-color="#ff4949">
    </el-switch>
    <el-button v-if="draggable" @click="editSort">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" show-checkbox node-key="catId"
      @node-drop="handleDrop" :expand-on-click-node="false" :default-expanded-keys="expandKeys" :draggable="draggable"
      :allow-drop="allowDrop" ref="tree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button v-if="data.catLevel <= 2" type="text" size="mini" @click="() => append(data)">
            添加
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            修改
          </el-button>
          <el-button v-if="data.childrens && data.childrens.length === 0" type="text" size="mini" @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="dialogType ? '新增' : '修改'" :visible.sync="dialogFormVisible" width="30%"
      :close-on-click-modal="false">
      <el-form :model="categoryForm">
        <el-form-item label="类别名称" :label-width="formLabelWidth">
          <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类别图标" :label-width="formLabelWidth">
          <el-input v-model="categoryForm.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位" :label-width="formLabelWidth">
          <el-input v-model="categoryForm.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  data() {
    return {
      data: [],
      expandKeys: [],
      defaultProps: {
        children: 'childrens',
        label: 'name'
      },
      dialogFormVisible: false, // 新增表单显示
      categoryForm: {}, // 新增表单
      dialogType: true, // 判断是新增还是修改操作 false为修改操作，true为新增操作
      draggable: false, // 拖拽功能默认是关闭的
      maxLevel: 0,
      updateNodes: [], // 拖拽节点后，需要更新的节点的节点信息
      formLabelWidth: '15%',
      pCid: [],
    }
  },
  methods: {
    batchDelete() {
      let ids = [];
      this.$refs.tree.getCheckedNodes(false, false).forEach(item => {
        console.log(item);
        ids.push(item.catId);
      });
      // 给出一个删除的提示信息
      this.$confirm(`是否确认删除【${ids}】记录?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 把删除的请求提交到后台服务
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              // 重新加载所有的菜单数据
              this.getCategory();
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleNodeClick(data) {
      console.log(data)
    },
    // draggingNode 要拖拽的节点
    // dropNode 目标节点
    // type 参数有三种情况：'prev'、'inner' 和 'next'
    handleDrop(draggingNode, dropNode, type, event) {
      // 1. 拖拽节点的父节点需要修改
      let parentId = 0;
      // 找到拖拽节点对应的所有的兄弟节点
      let siblings = null;
      if (type == 'inner') {
        parentId = dropNode.data.catId;
        siblings = dropNode.childNodes;
      } else {
        parentId = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId;
        siblings = dropNode.parent.childNodes;
      }
      // 2. 拖拽后节点所在的新的兄弟节点间的排序问题
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          // 获取的就是拖拽的那个节点，那么我们需要更新parent_cid
          // 3. 拖拽后的节点及其节点的的 catLevel 更新问题
          let catLevel = draggingNode.level;
          if (siblings[i].level != catLevel) {
            // 拖拽后节点的层级发生了变化，
            catLevel = siblings[i].level;
            // 递归的方式来更新子节点的层级
            this.updateChildNodeLevel(siblings[i]);
          }
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i, parentCid: parentId, catLevel: catLevel })
        } else {
          this.updateNodes.push({ catId: siblings[i].data.catId, sort: i })
        }
      }
      console.log("--->", this.updateNodes)
      this.pCid.push(parentId);
      // 将需要更新的数据提交到后端服务处理
      //this.editSort(parentId);
      // 在一次拖拽操作完成后重置相关的数据
      //this.updateNodes=[];
      //this.maxLevel=0;

    },
    updateChildNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          var childNode = node.childNodes[i].data;
          this.updateNodes.push({ catId: node.childNodes.catId, catLevel: node.childNodes[i].level });
          // 如果还有子节点，同步的更新处理
          this.updateChildNodeLevel(node.childNodes[i]);
        }
      }
    },
    editSort() {
      // 获取最新的数据回写
      this.$http({
        url: this.$http.adornUrl(`/product/category/updateBatch`),
        method: "post",
        data: this.$http.adornData(this.updateNodes, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "拖拽操作成功",
            type: "success",
          });
          // 重新加载所有的菜单数据
          this.getCategory();
          // 设置默认展开的父节点信息
          this.expandKeys = this.pCid;
          // 提交更新的数据后，重新相关的数据
          this.updateNodes = [];
          this.maxLevel = 0;
          console.log("parentCid:", this.pCid)
          this.parentCid = [];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    allowDrop(draggingNode, dropNode, type) {
      // 判断拖拽的节点是否可以在该位置放置
      console.log("--->", draggingNode, dropNode, type)
      this.countNodeLevel(draggingNode);
      console.log(this.maxLevel)
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      if (type == 'inner') {
        return deep + dropNode.level <= 3;
      }
      return deep + dropNode.parent.level <= 3;
    },
    countNodeLevel(node) {
      this.maxLevel = node.data.catLevel
      // 找到所有子节点，最大的level
      if (node.childNodes != null && node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          if (node.childNodes[i].level > this.maxLevel) {
            this.maxLevel = node.childNodes[i].level
          }
          this.countNodeLevel(node.childNodes[i]);
        }
      }
    },
    getCategory() {
      this.$http({
        url: this.$http.adornUrl('/product/category/queryCategoryByTree'),
        method: 'get'
      }).then(({ data }) => {
        this.data = data.categoryTree
      })
    },
    submitForm() {
      if (this.dialogType) {
        this.addDialog()
      } else {
        this.editDialog()
      }
    },
    edit(data) {
      this.dialogType = false
      this.dialogFormVisible = true
      this.categoryForm = data
      console.log("修改", data)
    },
    append(data) {
      this.dialogFormVisible = true
      this.categoryForm = {
        parentCid: data.catId,
        catLevel: data.catLevel + 1,
        sort: 0,
        showStatus: 1,
      }
      console.log("添加", data)
    },
    addDialog() {
      this.dialogFormVisible = false
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          // 重新加载所有的菜单数据
          this.getCategory();
          // 设置默认展开的父节点信息
          this.expandKeys = [this.categoryForm.parentCid];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    editDialog() {
      this.dialogFormVisible = false
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(this.categoryForm, false),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: "操作成功",
            type: "success",
          });
          // 重新加载所有的菜单数据
          this.getCategory();
          // 设置默认展开的父节点信息
          this.expandKeys = [this.categoryForm.parentCid];
        } else {
          this.$message.error(data.msg);
        }
      });
    },
    remove(node, data) {
      this.$confirm(`是否确认删除【${data.name}】记录?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 传递的数据
          let ids = [data.catId];
          // 把删除的请求提交到后台服务
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
              });
              // 重新加载所有的菜单数据
              this.getCategory();
              // 设置默认展开的父节点信息
              this.expandKeys = [node.parent.data.catId]
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      console.log("删除", data, node);
    },
  },
  created() {
    this.getCategory()
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
